package com.maikobi.maikobi.bizmq;


import com.maikobi.maikobi.common.ErrorCode;
import com.maikobi.maikobi.constant.BiConstant;
import com.maikobi.maikobi.constant.BiMqConstant;
import com.maikobi.maikobi.exception.BusinessException;
import com.maikobi.maikobi.manager.AiManager;
import com.maikobi.maikobi.model.entity.Chart;
import com.maikobi.maikobi.model.enums.ChartStatus;
import com.maikobi.maikobi.service.ChartService;
import com.maikobi.maikobi.utils.DingTalkNotifier;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class BiMessageConsumer {

    @Resource
    private ChartService chartService;

    @Resource
    private AiManager aiManager;

    @Resource
    private DingTalkNotifier dingTalkNotifier;

    /**
     * 普通队列消息消费
     */
    @SneakyThrows
    @RabbitListener(queues = {BiMqConstant.BI_QUEUE_NAME}, ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        log.info("接收到消息：{}", message);
        if (StringUtils.isBlank(message)) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "消息为空");
        }

        long chartId;
        try {
            chartId = Long.parseLong(message);
        } catch (NumberFormatException e) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "消息格式错误");
        }

        Chart chart = chartService.getById(chartId);
        if (chart == null) {
            channel.basicNack(deliveryTag, false, false);
            throw new BusinessException(ErrorCode.USER_NOT_EXIST, "图表不存在");
        }

        // 更新状态为运行中
        Chart updateChart = new Chart();
        updateChart.setId(chart.getId());
        updateChart.setStatus(ChartStatus.RUNNING);
        boolean updateStatusResult = chartService.updateById(updateChart);
        if (!updateStatusResult) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表运行中状态失败");
            return;
        }

        // 调用AI
        String result = aiManager.doChat(BiConstant.BI_MODEL_ID, buildUserInput(chart));
        String[] splits = result.split("【【【【【");
        if (splits.length < 3) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "AI生成结果格式异常");
            return;
        }

        String genChart = splits[1].trim();
        String genResult = splits[2].trim();

        Chart updateChartResult = new Chart();
        updateChartResult.setId(chart.getId());
        updateChartResult.setGenChart(genChart);
        updateChartResult.setGenResult(genResult);
        updateChartResult.setStatus(ChartStatus.SUCCEED);
        boolean updateResult = chartService.updateById(updateChartResult);

        if (!updateResult) {
            channel.basicNack(deliveryTag, false, false);
            handleChartUpdateError(chart.getId(), "更新图表成功状态失败");
            return;
        }

        // 手动确认消息
        channel.basicAck(deliveryTag, false);
    }

    /**
     * 构建AI输入文本
     */
    private String buildUserInput(Chart chart) {
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：\n");
        String userGoal = chart.getGoal();
        if (StringUtils.isNotBlank(chart.getChartType())) {
            userGoal += "，请使用" + chart.getChartType();
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：\n");
        userInput.append(chart.getChartData()).append("\n");
        return userInput.toString();
    }

    /**
     * 更新失败状态处理
     */
    private void handleChartUpdateError(long chartId, String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(ChartStatus.FAILED);
        updateChartResult.setExecMessage(execMessage);
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表失败状态失败: chartId={}, msg={}", chartId, execMessage);
        }
    }


    /**
     * 死信队列消息监听 - 这里可以做补偿处理或报警
     */
    @RabbitListener(queues = BiMqConstant.BI_DEAD_QUEUE_NAME)
    public void receiveDeadLetterMessage(String message) {
        log.error("死信队列收到消息：{}", message);
        // 这里你可以写报警逻辑、补偿逻辑、人工介入逻辑等
        log.error("❌ 死信队列收到失败的图表消息，chartId: {}", message);

        // 补偿逻辑
        Long chartId = Long.valueOf(message);
        handleChartUpdateError(chartId, "图表生成失败，已进入死信队列。");

        // 钉钉告警
        String alert = String.format("⚠️ BI图表生成失败！\n图表ID: %d\n请尽快处理。", chartId);
        dingTalkNotifier.sendTextMessage(alert);
    }
}
